﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Runtime.Serialization;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
//using System.Object;
using System.IO;
using Newtonsoft.Json;
using HTSwitchServerNamespace;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;


namespace GoogleClassNamespace
{
    public class GoogleService
    {
        ////////////////////////////////GOOGLE CELL ID /////////////////////////////////
        public GoogleCell GetCellInfo(string lac, string mnc, string mcc, string cellID, string strSignalstren)
        {
            try 
            {
                //HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/loc/json");
               // HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://code.google.com/p/gears/wiki/GeolocationAPI");

                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(@"http://www.google.com/loc/json");

                myReq.Method = "POST";
                myReq.ContentType = "application/jsonrequest";

                //EJEMPLO GOOGLE //
                //string postData ="{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"home_mobile_country_code\":\"310\",\"home_mobile_network_code\": \"410\",\"radio_type\": \"gsm\",\"carrier\": \"Vodafone\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"51.0\",\"longitude\": \"-0.1\"},\"cell_towers\": [{\"cell_id\": \"42\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"410\",\"age\": \"0\",\"signal_strength\": \"-60\",\"timing_advance\": \"5555\"},{\"cell_id\": \"88\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"580\",\"age\": \"0\",\"signal_strength\": \"-70\",\"timing_advance\": \"7777\"}],\"wifi_towers\": [{\"mac_address\": \"01-23-45-67-89-ab\",\"signal_strength\": 8,\"age\": \"0\"},{\"mac_address\": \"01-23-45-67-89-ac\",\"signal_strength\": \"4\",\"age\": \"0\"}]}";
                //string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"0\",\"longitude\": \"0\"},\"cell_towers\": [{\"cell_id\": \"42\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"410\",\"age\": \"0\",\"signal_strength\": \"-60\",\"timing_advance\": \"5555\"},{\"cell_id\": \"88\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"580\",\"age\": \"0\",\"signal_strength\": \"-70\",\"timing_advance\": \"7777\"}],\"wifi_towers\": [{\"mac_address\": \"01-23-45-67-89-ab\",\"signal_strength\": 8,\"age\": \"0\"},{\"mac_address\": \"01-23-45-67-89-ac\",\"signal_strength\": \"4\",\"age\": \"0\"}]}";

            //string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"carrier\": \"Personal\",\"request_address\": \"true\",\"address_language\": \"es_ES\", \"location\": { \"latitude\": \"-34.5\",\"longitude\": \"-59.9\"},\"cell_towers\": [{\"cell_id\": \"42\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"410\",\"signal_strength\": \"" + strSignalstren + "\"}]}";

                //string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"access_token\": \"2:wuIT-T8fUUq-h_Hu:E8eOS0EfrrvmpZ03\", \"radio_type\": \"gsm\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"0\",\"longitude\": \"0\"},\"cell_towers\": [{\"cell_id\": \"42\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"410\"}]}";
                //end ejemplo
                
                //string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"0\",\"longitude\": \"0\"},\"cell_towers\": [{\"cell_id\": \"42\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"410\",\"age\": \"0\",\"signal_strength\": \"-60\",\"timing_advance\": \"5555\"},{\"cell_id\": \"88\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"580\",\"age\": \"0\",\"signal_strength\": \"-70\",\"timing_advance\": \"7777\"}],\"wifi_towers\": [{\"mac_address\": \"01-23-45-67-89-ab\",\"signal_strength\": 8,\"age\": \"0\"},{\"mac_address\": \"01-23-45-67-89-ac\",\"signal_strength\": \"4\",\"age\": \"0\"}]}";
                //string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"0\",\"longitude\": \"0\"},\"cell_towers\": [{\"cell_id\": \"" + cellID +"\",\"location_area_code\": \"" + lac + "\",\"mobile_country_code\": \"" + mcc + "\",\"mobile_network_code\": \"" + mnc + "\",\"age\": \"0\",\"signal_strength\": \"-60\",\"timing_advance\": \"5555\"},{\"cell_id\": \"88\",\"location_area_code\": \"415\",\"mobile_country_code\": \"310\",\"mobile_network_code\": \"580\",\"age\": \"0\",\"signal_strength\": \"-70\",\"timing_advance\": \"7777\"}],\"wifi_towers\": [{\"mac_address\": \"01-23-45-67-89-ab\",\"signal_strength\": 8,\"age\": \"0\"},{\"mac_address\": \"01-23-45-67-89-ac\",\"signal_strength\": \"4\",\"age\": \"0\"}]}";
                // string postData = "{\"version\": \"1.0.1\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"request_address\": \"true\",\"address_language\": \"en_GB\", \"location\": { \"latitude\": \"0\",\"longitude\": \"0\"},\"cell_towers\": [{\"cell_id\": \"" + cellID + "\",\"location_area_code\": \"" + lac + "\",\"mobile_country_code\": \"" + mcc + "\",\"mobile_network_code\": \"" + mnc + "\",\"signal_strength\": \"" + strSignalstren + "\"}]}";

            string postData = "{\"version\": \"1.1.0\",\"host\": \"maps.google.com\",\"radio_type\": \"gsm\",\"carrier\": \"Personal\",\"request_address\": \"true\",\"address_language\": \"es_ES\", \"location\": { \"latitude\": \"-34.5\",\"longitude\": \"-59.3\"},\"cell_towers\": [{\"cell_id\": \"" + cellID + "\",\"location_area_code\": \"" + lac + "\",\"mobile_country_code\": \"" + mcc + "\",\"mobile_network_code\": \"" + mnc + "\",\"signal_strength\": \"" + strSignalstren + "\"}]}";

                //"access_token":"2:wuIT-T8fUUq-h_Hu:E8eOS0EfrrvmpZ03"

                myReq.ContentLength = postData.Length;

                StreamWriter stOut = new StreamWriter(myReq.GetRequestStream(), System.Text.Encoding.ASCII);
                stOut.Write(postData);
                stOut.Close();
                CLogger.Append("POSTDATA = " + postData, CLogger.INFO);

                HttpWebResponse webresponse;
                webresponse = (HttpWebResponse)myReq.GetResponse();
                Encoding enc = System.Text.Encoding.UTF8;
                StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);

                string Response = loResponseStream.ReadToEnd();
                // CLogger.Append("RESPONSE: = "+ Response, CLogger.INFO);  //DEBUG

                loResponseStream.Close();
                webresponse.Close();
                
                GoogleCell Mycell = JsonConvert.DeserializeObject<GoogleCell>(Response);

                Mycell.Signal = strSignalstren;
                CLogger.Append("RESPONSE: Latitud: " + Mycell.location.latitude + " Longitud: "+Mycell.location.longitude, CLogger.INFO); //DEBUG

                if ((Mycell.location.latitude == null) || (Mycell.location.longitude == null)||
                    (Convert.ToDouble(Mycell.location.latitude)==0)||(Convert.ToDouble(Mycell.location.longitude)==0))
                {
                    throw new Exception("Coordenadas de la antena inválidas");
                }
                return Mycell;
            }
            catch (Exception ex)
            {
                CLogger.Append("ERROR API GOOGLECELL:  " + ex, CLogger.ERROR);
                throw ex;           
            }            
        }

        
        /// //////////////////////////////////OPEN CELL ID///////////////////////////////
        /// </summary>
        /// <param name="lac"></param>
        /// <param name="mnc"></param>
        /// <param name="mcc"></param>
        /// <param name="cellID"></param>
        /// <returns></returns>

        public GoogleCell GetCellInfo_OpenCellID(string lac, string mnc, string mcc, string cellID, string strSignal)
        {
           
            string API = "2b247be8b989187aaf63c861ddb6c444";
            /// Mi API: 2b247be8b989187aaf63c861ddb6c444
            try
            {
             //   CLogger.Append("Lac = " + lac, CLogger.INFO);     //DEBUG
                //  CLogger.Append("MNC = " + mnc, CLogger.INFO);   //DEBUG
                 //    CLogger.Append("MCC = " + mcc, CLogger.INFO);    //DEBUG
                // CLogger.Append("CELLID = " + cellID, CLogger.INFO);  //DEBUG
              //  CLogger.Append("CELLID = " + cellID + " - Lac = " + lac + " - Signal = " + strSignal , CLogger.INFO);     //DEBUG

               // HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format("http://www.opencellid.org/cell/get?mcc={0}&mnc={1}&cellid={2}&lac={3}", mcc, mnc, cellID, lac));
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format("http://www.opencellid.org/cell/get?key={0}&mcc={1}&mnc={2}&cellid={3}&lac={4}",API,mcc, mnc, cellID, lac));
             //   HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format("http://www.opencellid.org/cell/get?mcc=250&mnc=99&cellid=29513&lac=0"));

                HttpWebResponse webresponse;
                webresponse = (HttpWebResponse)myReq.GetResponse();
                //Encoding enc = System.Text.Encoding.UTF8;

                StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream());

                string Response = loResponseStream.ReadToEnd();
                loResponseStream.Close();
                webresponse.Close();

               //  CLogger.Append("RESPONSE = " + Response, CLogger.INFO);  //DEBUG
                GoogleCell Mycell = new GoogleCell();

                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(Response);          
                
                string strlat = xdoc.ChildNodes[1].FirstChild.Attributes["lat"].Value;
                //CLogger.Append("PASE XML LAT = " + strlat, CLogger.INFO);         //DEBUG
                
                
                //Mycell.location.latitude = xdoc.FirstChild.ChildNodes[1].Attributes["lat"].Value;

                string strlon = xdoc.ChildNodes[1].FirstChild.Attributes["lon"].Value;
               // CLogger.Append("PASE XML LON = " + strlon, CLogger.INFO); //DEBUG

                CLogger.Append("RESPONSE: Latitud = " + strlat + " - Longitud = " + strlon, CLogger.INFO); //DEBUG

                //Mycell.location.latitude = Convert.ToString(xdoc.ChildNodes[1].FirstChild.Attributes["lat"].Value);
                //CLogger.Append("PASE XML LAT = " + Mycell.location.latitude, CLogger.INFO);
               // Mycell.location.latitude = xdoc.FirstChild.ChildNodes[1].Attributes["lon"].Value;
                //Mycell.location.longitude = Convert.ToString( xdoc.ChildNodes[1].FirstChild.Attributes["lon"].Value);
                //CLogger.Append("PASE XML LONG = " + Mycell.location.longitude, CLogger.INFO);
                Mycell.location.latitude = strlat;   
                Mycell.location.longitude = strlon;
                Mycell.Mcc = mcc;
                Mycell.CellID = cellID;
                Mycell.Mnc = mnc;
                Mycell.Signal = strSignal;
                //CLogger.Append("MYCELLLOCATIONLAT = " + Mycell.location.latitude, CLogger.INFO);
                //CLogger.Append("MYCELLLOCATIONLON = " + Mycell.location.longitude, CLogger.INFO);
                //MessageBox.Show(xdoc.ChildNodes[0].InnerText);

                if ((Mycell.location.latitude == null) || (Mycell.location.longitude == null) ||
                (Convert.ToDouble(Mycell.location.latitude) == 0) || (Convert.ToDouble(Mycell.location.longitude) == 0))
                {
                    throw new Exception("Coordenadas de la antena inválidas");
                }
                return Mycell;
            }
            catch (Exception ex)
            {
                CLogger.Append("ERROR API OPEN CELL:  " + ex, CLogger.ERROR);
                throw ex;     
            }              
        }
    }

    public class GoogleCell
    {
        public GoogleCell() { }
        public GoogleCell(string mnc, string mcc, string lac)
        {
            this.Mnc = mnc;
            this.Mcc = mcc;
            this.Lac = lac;
        }

        public string Mnc { get; set; }
        public string Mcc { get; set; }
        public string Lac { get; set; }
        public string CellID { get; set; }
        public string Signal { get; set; }
        public Location location = new Location();

        public class Location
        {
            public Location() { }
            public Location(string latitude, string longitude)
            {
                this.latitude = latitude;
                this.longitude = longitude;
            }
            public string latitude { get; set; }
            public string longitude { get; set; }
            public Address address = new Address();

            public class Address
            {
                public Address() { }
                public string country { get; set; }
                public string country_code { get; set; }
                public string city { get; set; }
                public string region { get; set; }
                public string street { get; set; }
                public string street_number { get; set; }
                public string postal_code { get; set; }
            }
        }
    }
}
/*
public class JSONHelper
{
    public static string Serialize<T>(T obj)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        string retVal = Encoding.Default.GetString(ms.ToArray());
        ms.Dispose();
        return retVal;
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        ms.Dispose();
        return obj;
    }
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}


/// Sample code using the above helper methods
/// to serialize and deserialize the Person object

Person myPerson = new Person("Chris", "Pietschmann");

// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);

// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);
 */
 
